﻿using Microsoft.Data.Sqlite;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace DataBaseFactory
{
    /// <summary>
    /// 连接对象工厂
    /// </summary>
    public class ConnectionFactory
    {
        /// <summary>
        /// 数据库连接集合
        /// </summary>
        private static ConcurrentDictionary<DBTypeEnum, IDbConnection> DBS = new ConcurrentDictionary<DBTypeEnum, IDbConnection>();

        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <param name="dbType"></param>
        /// <param name="connectString"></param>
        /// <returns></returns>
        public static IDbConnection GetConnection(DBTypeEnum dbType, string connectString)
        {
            if (DBS.ContainsKey(dbType)) return DBS[dbType];

            IDbConnection cnn = dbType switch
            {
                DBTypeEnum.MSSQL => new SqlConnection(connectString),
                DBTypeEnum.SQLite => new SqliteConnection(connectString),
                _ => throw new NotImplementedException($"暂未支持{dbType}数据库。"),
            };

            DBS.TryAdd(dbType, cnn);

            return cnn;
        }

        /// <summary>
        /// 移除数据库连接
        /// </summary>
        /// <param name="dbType"></param>
        public static bool RemoveConnection(DBTypeEnum dbType)
        {
            if (DBS.ContainsKey(dbType))
            {
                var dbconn = DBS[dbType];
                dbconn.Close();
                dbconn.Dispose();
                return DBS.TryRemove(dbType, out _);
            }
            return false;
        }
    }
}
